package com.easy.controller;

import com.easy.bean.Tadmin;
import com.easy.service.AdminService;
import com.easy.util.DeCodeUtil;
import com.easy.util.JWTUtil;
import com.easy.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@RequestMapping("admin")
@RestController
@CrossOrigin
public class AdminController {

//    public List getList(){}
    @Autowired
    AdminService adminService;

    @GetMapping("list")
    public Result getList(){
      List<Tadmin> list= adminService.list();
      return Result.success(list);
    }

    @PostMapping
    public Result add(@RequestBody  Tadmin tadmin){
        //admin   的密码是123456    将密码加密存入数据库
        String pass=tadmin.getPassword();
        String newpass=DeCodeUtil.decode(pass);
        tadmin.setPassword(newpass);
        adminService.save(tadmin);
        Tadmin admin= adminService.getById(tadmin.getId());
        return Result.success("保存成功",tadmin);
    }

@DeleteMapping("/{id}")
    public Result delete(@PathVariable("id")  Integer id){
        boolean b=adminService.removeById(id);
        if(b){
            return Result.success("删除成功");
        }else{
            return Result.fail(201,"删除失败");
        }
    }
    @PutMapping
    public Result edit(@RequestBody Tadmin admin){
        boolean b=adminService.saveOrUpdate(admin);
        Tadmin tadmin=adminService.getById(admin.getId());
        if(b){
            return Result.success("保存成功",tadmin);
        }else{
            return Result.fail(201,"修改失败");
        }
    }
    @PostMapping("login")
    public Result login( Tadmin admin,@RequestParam("code") String code){
        //验证码是否正确

        //通过用户名查询用户的信息
            Tadmin admin_data=adminService.selectByName(admin.getPhone());
        //如果有信息，就比对密码是否正确
            if(admin_data!=null){
                //加密前端传入的数据和数据库中的密码进行比较
               boolean check= DeCodeUtil.decode(admin.getPassword()).equals(admin_data.getPassword());
               if(check){
                   //如果比对正确登陆成功,签发token
                    String token= JWTUtil.getToken();
                    return Result.success("登陆成功",token);
               }
            }
        return Result.fail(401,"认证失败");
    }
    //vue   要求严格的数据返回格式
//    {code： msg；  data}

}
